
#!/bin/bash

# 定义historyLock文件夹路径
historyLockDir="historyLock"
logDir="${historyLockDir}/log"

typeDir="package-lock.json"


if [[ "$1" == "yarn" ]]; then
    typeDir="yarn.lock"
    echo "Yarn lock file detected."
fi


# 检查historyLock文件夹是否存在
if [ ! -d "$historyLockDir" ]; then
    # 如果不存在，则创建文件夹
    mkdir "$historyLockDir"
    if [ ! -d "$logDir" ]; then
      mkdir "$logDir"
      echo "Created directory: $logDir"
    fi
    echo "Created directory: $historyLockDir"
else
    # 如果存在，检查$typeDir文件是否在该文件夹中
    if [ -f "$historyLockDir/$typeDir" ]; then
        # 如果存在，替换当前目录下的package-lock.json文件
        cp "$historyLockDir/$typeDir" "./$typeDir"
        echo "Replaced $typeDir with the one from $historyLockDir"
    fi
fi

if [[ "$1" == "yarn" ]]; then
  yarn
else 
  npm i
fi

if [[ -f "$typeDir" ]]; then
    echo "$typeDir update."
    # 获取当前时间并格式化为YYYYMMDD-HHMMSS格式
    currentTime=$(date +"%Y%m%d-%H%M%S")
    # 如果historyLock目录下已经存在package-lock.json，则重命名并移动到log目录
    if [[ -f "${historyLockDir}/$typeDir" ]]; then
        if [[ "$1" == "yarn" ]]; then
          mv "${historyLockDir}/$typeDir" "${logDir}/${currentTime}.lock"
          echo "Moved historyLock/$typeDir to ${logDir}/${currentTime}.lock"
        else 
          mv "${historyLockDir}/$typeDir" "${logDir}/${currentTime}.json"
          echo "Moved historyLock/$typeDir to ${logDir}/${currentTime}.json"
        fi
       
    fi
    # 将当前目录下的package-lock.json复制到historyLock目录下
    cp "$typeDir" "${historyLockDir}/"
else
    echo "No $typeDir found in the current directory."
fi

